package cn.tedu.boot02.controller;

import cn.tedu.boot02.entity.User;
import cn.tedu.boot02.utils.DBUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@RestController
public class UserController {
    @RequestMapping("/reg")
    public String reg(User user) {
        System.out.println("user=" + user);
        try (Connection conn = DBUtil.getConnection()) {
            String sql = "SELECT id FROM user WHERE username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return "用户名已存在";
            }
            String insertSQL = "INSERT INTO user VALUES(NULL,?,?,?)";
            PreparedStatement insertPS = conn.prepareStatement(insertSQL);
            insertPS.setString(1, user.getUsername());
            insertPS.setString(2, user.getPassword());
            insertPS.setString(3, user.getNickname());
            insertPS.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return "注册成功!";

    }
    @RequestMapping("/login")
    public String login(User user){
        System.out.println("user = " + user);
        try (Connection conn = DBUtil.getConnection()){
            //通过用户输入的用户名查询数据库中的密码
            String sql = "SELECT password FROM user WHERE username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ResultSet rs = ps.executeQuery();
            //判断是否查询到了
            if (rs.next()){
                //执行到这里代表查询到了  说明用户名存在
                String pw = rs.getString(1);//得到数据库中查询到的密码
                //判断数据库里查询到的和用户输入的是否一致
                if (pw.equals(user.getPassword())){
                    return "登录成功!";
                }
                return "密码错误!";
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return "用户名不存在!";
    }
}
